#include <iostream>
#include <fstream>
#include <assert.h>
#include <opencv2/opencv.hpp>
#include "decode_yuv420sp_nv21.h"
#include "face_detect.h"
#define LOG_TAG __FILE__
#include "tools.h"

using namespace std;
using namespace cv;

#define WIDTH 1920
#define HEIGHT 1080
//#define CASCADE_FACE "/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml"

static CvHaarClassifierCascade * faceCascade = NULL;
int main(int argc, char *argv[]) {
    assert(argc > 2);

    const char *CASCADE_FACE = argv[1];
    if (faceCascade == NULL) {
        LOGD("cascade file: %s", CASCADE_FACE);
        faceCascade = (CvHaarClassifierCascade*)cvLoad(CASCADE_FACE, 0, 0, 0 );
    }

    for (int i = 2; i < argc; i++) {

#ifndef USE_LOAD
        std::ifstream is (argv[i], ifstream::binary);
        if (is) {
            // get length of file:
            is.seekg (0, is.end);
            int length = is.tellg();
            is.seekg (0, is.beg);

            assert((WIDTH*HEIGHT + (WIDTH*HEIGHT/2)) == length);

            char * buffer = new char [length];

            std::cout << "Reading " << length << " characters... " << endl;
            // read data as a block:
            is.read (buffer,length);

            if (is)
                std::cout << "all characters read successfully." << endl;
            else
                std::cout << "error: only " << is.gcount() << " could be read" << endl;

            is.close();
# ifdef USE_INT
            int *rgb = new int[WIDTH*HEIGHT];
            decodeYuv420sp_0rgb(rgb, buffer, WIDTH, HEIGHT);
# endif //def USE_INT

# ifdef USE_CHAR
            char *rgb = new char[WIDTH*HEIGHT*4];
            decodeYuv420sp_bgr0(rgb, buffer, WIDTH, HEIGHT);
# endif //def USE_CHAR

            IplImage *iplBGRA = cvCreateImageHeader(cvSize(WIDTH,HEIGHT), IPL_DEPTH_8U, 4);
            cvSetData(iplBGRA, (char *)rgb, iplBGRA->widthStep);
#else
            IplImage *iplBGRA = cvLoadImage(argv[i]);
#endif

            vector<CvRect> *vectRects = new vector<CvRect>(); 
            face_detect(iplBGRA, vectRects, faceCascade, false);

            cvNamedWindow("win1", CV_WINDOW_AUTOSIZE);
            cvMoveWindow("win1", 0, 0);
            cvShowImage("win1", iplBGRA);
            cvWaitKey(0);

            // release resources
            cvReleaseImageHeader(&iplBGRA);
            cvDestroyWindow("win1");

#ifndef USE_LOAD
            delete[] rgb;
            delete[] buffer;
        }
#endif
    }

    return 0;
}
